package employeedb;

import java.io.*;
import java.util.LinkedList;

/**
 *
 * @author Админ
 */
public class WorkerIO {
    /**
     *
     * фция читает из заданного файла создавая список работников
     */
    public static LinkedList<Worker> readFromFile(String fileName) throws FileNotFoundException, IOException {
        FileReader tmp = new FileReader(fileName);
        BufferedReader reader = new BufferedReader(tmp);
        LinkedList<String> workerList = new LinkedList();
        String str = "";
        while ((str = reader.readLine()) != null) {
            workerList.add(str);
        }
        LinkedList<Worker> newWorkerList = new LinkedList();
        while (workerList.isEmpty() == false) {
            String[] tmpStructure1 = workerList.removeLast().split(";");
            String[] tmpStructure2 = tmpStructure1[2].split(",");
            LinkedList<Project> projects = new LinkedList<Project>();
            for (int i = 0; i < tmpStructure2.length; i++) {
                projects.add(new Project(tmpStructure2[i], tmpStructure2[i].contains("fixed Cost")));
            }
            newWorkerList.add(new Worker(tmpStructure1[0], tmpStructure1[1], projects, Double.valueOf(tmpStructure1[3]), Double.valueOf(tmpStructure1[4])));
        }
        reader.close();
        return newWorkerList;
    }

    public static void writeToFile(LinkedList<Worker> newWorkerList,String fileName) throws IOException {
       /* for (int i = 0; i < newWorkerList.size(); i++) {
            newWorkerList.get(i).payroll();
        }

        WorkerHandler.sort(newWorkerList);
       */
        FileWriter w = new FileWriter(fileName);
        while (newWorkerList.isEmpty() == false) {
            w.write(newWorkerList.getFirst().getEmployee() + " " + newWorkerList.removeFirst().getPayroll() + "\r\n");
        }
        w.close();
    }
}
